package com.woniu.lottery.service.impl;

import com.woniu.lottery.entity.LotteryPrize;
import com.woniu.lottery.mapper.LotteryPrizeMapper;
import com.woniu.lottery.service.ILotteryPrizeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author mane
 * @since 2025-04-13
 */
@Service
public class LotteryPrizeServiceImpl extends ServiceImpl<LotteryPrizeMapper, LotteryPrize> implements ILotteryPrizeService {

    @Autowired
    private LotteryPrizeMapper lotteryPrizeMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    //执行抽奖算法,先构建抽奖上下文
    @Override
    @Cacheable(
            value = "lotteryPrizes",
            key = "#activityId",
            unless = "#result != null && #result.size() > 0"
    )
    public List<LotteryPrize> getCachedPrizesByActivityId(Long activityId) {
        System.out.println("查询数据库...");
        List<LotteryPrize> prizes = lotteryPrizeMapper.getPrizesByActivityId(activityId);
        // 防御缓存穿透：空结果缓存5分钟
        if (prizes == null || prizes.isEmpty()) {
            redisTemplate.opsForValue().set(
                    "lotteryPrizes::" + activityId,
                    Collections.emptyList(),
                    Duration.ofMinutes(5)
            );
        }
        return prizes;
    }
}
